import { Component, OnInit, OnDestroy } from '@angular/core'
import { NzMessageService } from 'ng-zorro-antd'
import { Router, ActivatedRoute } from '@angular/router'
import { PageService } from '@shared/services/page.service'
import { ComWindow } from '@shared/classes/ComWindowClass'
import { INewPageColumn } from '@shared/interfaces/common'
import { RiskRuleNewBaseComponent } from './base/base.component'
import { RiskRuleStoreService } from './rule-store.service'
import { RiskService } from '../../risk.service'
import { I18NService } from '@core'

@Component({
  selector: 'app-risk-rule-new',
  templateUrl: './new.component.html',
})
export class RiskRuleNewComponent implements OnInit, OnDestroy {
  pages: INewPageColumn[] = []

  schemeCode: string

  constructor(
    public msg: NzMessageService,
    public router: Router,
    public route: ActivatedRoute,
    public pageService: PageService,
    private riskRuleStore: RiskRuleStoreService,
    private riskService: RiskService,
    private i18n: I18NService,
  ) { }

  ngOnInit() {
    this.schemeCode = this.route.snapshot.params['id']
    this.initColumns()
  }

  ngOnDestroy() {
    this.riskRuleStore.reset()
  }

  initColumns(): void {
    this.pages = [
      {
        component: new ComWindow(RiskRuleNewBaseComponent, { title: '新增风控规则' })
      }
    ]
  }

  submit(): void {
    const rule = this.riskRuleStore.value
    rule.type = rule.level ? 'refund' : 'quota'

    this.riskService
      .createRule(this.schemeCode, rule)
      .subscribe(
        () => {
          this.msg.success(this.trans('GENERAL.NOTIFICATION.CREATE_SUCCESS'))
          this.router.navigate(['../'], { relativeTo: this.route })
        },
        (err) => {
          this.msg.error(this.trans('GENERAL.NOTIFICATION.CREATE_FAIL'))
        }
      )
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
